package com.gyj.activiti.controller;

import com.gyj.activiti.dao.mapper.ApplyInfoMapper;
import com.gyj.activiti.dao.mapper.ApproveInfoMapper;
import com.gyj.activiti.service.ActivitiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "测试相关接口")
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ActivitiService activitiService;

    @Autowired
    private ApplyInfoMapper applyInfoMapper;

    @Autowired
    private ApproveInfoMapper approveInfoMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    /**
     * 获取默认流程引擎实例，会自动读取activiti.cfg.xml文件
     */
    private ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

    @GetMapping("/helloWorld")
    public void helloWorld() {
        //根据bpmn文件部署流程  
        Deployment deploy = repositoryService.createDeployment()

                .addClasspathResource("TestProcess.bpmn").name("请假流程").deploy();
        System.out.println("流程部署ID:" + deploy.getId());
        System.out.println("流程部署Name:" + deploy.getName());
        //获取流程定义  
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploy.getId()).singleResult();
        //启动流程定义，返回流程实例  
        ProcessInstance pi = runtimeService.startProcessInstanceById(processDefinition.getId());
        String processId = pi.getId();
        System.out.println("流程创建成功，当前流程实例ID：" + processId);
        Task task = taskService.createTaskQuery().processInstanceId(processId).singleResult();
        System.out.println("执行前，任务名称：" + task.getName());
        taskService.complete(task.getId());
        task = taskService.createTaskQuery().processInstanceId(processId).singleResult();
        System.out.println("task为null，任务执行完毕：" + task);
    }

    @ApiOperation(value = "测试singleAssignee")
    @GetMapping("/singleAssignee")
    public void setSingleAssignee() {
        //根据bpmn文件部署流程
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("singleAssignee.bpmn")
                .name("请假流程").name("studentForLeave").deploy();
        // 设置User Task1受理人变量
        Map<String, Object> map = new HashMap<>(5);
        map.put("aaa", "student11111");
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("singleAssignee", map);
        String processId = pi.getId();
        System.out.println("流程创建成功，当前流程实例ID：" + processId);

        //查看学生的任务列表，这里需要拿student来查询，key-value需要拿value来获取任务
        List<Task> list = taskService.createTaskQuery().taskAssignee("student11111").list();
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                System.out.println("任务ID：" + task.getId());
                System.out.println("任务的办理人：" + task.getAssignee());
                System.out.println("任务名称：" + task.getName());
                System.out.println("任务的创建时间：" + task.getCreateTime());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
            }
            // 设置User Task2的受理人变量
            Map<String, Object> variables1 = new HashMap<>(5);
            variables1.put("user2", "master");
            // 因为111只有一个代办的任务，直接完成任务，并赋值下一个节点的受理人user2为master办理
            taskService.complete(list.get(0).getId(), variables1);
            System.out.println("User Task1(学生请假)被完成了，此时流程已流转到User Task2（班主任）");
        }

        /**
         * 班主任审批
         */
        List<Task> masterList = taskService.createTaskQuery().taskAssignee("master").list();
        if (masterList != null && masterList.size() > 0) {
            for (Task task : masterList) {
                System.out.println("任务ID：" + task.getId());
                System.out.println("任务的办理人：" + task.getAssignee());
                System.out.println("任务名称：" + task.getName());
                System.out.println("任务的创建时间：" + task.getCreateTime());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
            }
            taskService.complete(masterList.get(0).getId());
            System.out.println("User Task2（班主任）完成了请假任务，流程结束");
        }
    }

    @ApiOperation(value = "测试simpleFlow2")
    @GetMapping("/simpleFlow2")
    public void simpleFlow() {
        //根据bpmn文件部署流程
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("111.bpmn").name("studentForLeave").deploy();
        //采用key来启动流程定义并设置流程变量，返回流程实例
        //ProcessInstance pi = runtimeService.startProcessInstanceByKey("myProcess");
        Map<String, Object> map = new HashMap<>(5);
        map.put("user111", "111");
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("myProcess111", map);
        String processId = pi.getId();
        System.out.println("流程创建成功，当前流程实例ID：" + processId);

        //查看学生的任务列表，这里需要拿student来查询，key-value需要拿value来获取任务
        List<Task> list = taskService.createTaskQuery().taskAssignee("111").list();
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                System.out.println("任务ID：" + task.getId());
                System.out.println("任务的办理人：" + task.getAssignee());
                System.out.println("任务名称：" + task.getName());
                System.out.println("任务的创建时间：" + task.getCreateTime());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
            }
            // 设置User Task2的受理人变量
            Map<String, Object> variables1 = new HashMap<>(5);
            variables1.put("days", 5);
            // 因为111只有一个代办的任务，直接完成任务，并赋值下一个节点的受理人user2为master办理
            taskService.complete(list.get(0).getId(), variables1);
            //System.out.println("User Task1(学生请假)被完成了，此时流程已流转到User Task2（班主任）");
        }

        /**
         * 班主任审批
         */
        List<Task> masterList = taskService.createTaskQuery().taskAssignee("master2").list();
        if (masterList != null && masterList.size() > 0) {
            for (Task task : masterList) {
                System.out.println("任务ID：" + task.getId());
                System.out.println("任务的办理人：" + task.getAssignee());
                System.out.println("任务名称：" + task.getName());
                System.out.println("任务的创建时间：" + task.getCreateTime());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
            }

            taskService.complete(masterList.get(0).getId());
        }
    }

    @ApiOperation(value = "测试multiAssignee")
    @GetMapping("/multiAssignee")
    public void setMultiAssignee() {

        //根据bpmn文件部署流程
        repositoryService.createDeployment().addClasspathResource("MultiAssignee.bpmn").deploy();
        // 设置多个处理人变量 这里设置了三个人
        Map<String, Object> variables = new HashMap<>();
        List<String> userList = new ArrayList<>();
        userList.add("user1");
        userList.add("user2");
        userList.add("user3");
        variables.put("userList", userList);
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("multiAssigneeProcess", variables);
        String processId = pi.getId();
        System.out.println("流程创建成功，当前流程实例ID：" + processId);

        // 查看user1的任务
        List<Task> list = taskService.createTaskQuery().taskAssignee("user1").list();
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                System.out.println("任务ID：" + task.getId());
                System.out.println("任务的办理人：" + task.getAssignee());
                System.out.println("任务名称：" + task.getName());
                System.out.println("任务的创建时间：" + task.getCreateTime());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
                System.out.println("#######################################");
            }
        }

        // 查看user2的任务
        List<Task> list2 = taskService.createTaskQuery().taskAssignee("user2").list();
        if (list2 != null && list2.size() > 0) {
            for (Task task : list2) {
                System.out.println("任务ID：" + task.getId());
                System.out.println("任务的办理人：" + task.getAssignee());
                System.out.println("任务名称：" + task.getName());
                System.out.println("任务的创建时间：" + task.getCreateTime());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
                System.out.println("#######################################");
            }
        }

        // 查看user3的任务
        List<Task> list3 = taskService.createTaskQuery().taskAssignee("user3").list();
        if (list3 != null && list3.size() > 0) {
            for (Task task : list3) {
                System.out.println("任务ID：" + task.getId());
                System.out.println("任务的办理人：" + task.getAssignee());
                System.out.println("任务名称：" + task.getName());
                System.out.println("任务的创建时间：" + task.getCreateTime());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
                System.out.println("#######################################");
            }
        }

    }

    @ApiOperation(value = "测试exclusiveGateway")
    @GetMapping("/exclusiveGateway")
    public void exclusiveGateway() {

        //根据bpmn文件部署流程
        repositoryService.createDeployment().addClasspathResource("exclusiveGateway.bpmn").deploy();
        // 设置User Task1受理人变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("user1", "007");
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("exclusiveGatewayAndTimerBoundaryEventProcess", variables);
        String processId = pi.getId();
        System.out.println("流程创建成功，当前流程实例ID：" + processId);

        // 注意 这里需要拿007来查询，key-value需要拿value来获取任务
        List<Task> list = taskService.createTaskQuery().taskAssignee("007").list();
        Map<String, Object> variables1 = new HashMap<>();
        variables1.put("user2", "lili"); // 设置User Task2的受理人变量
        variables1.put("operate", ""); // 设置用户的操作 为空 表示走flow3的默认路线
        taskService.complete(list.get(0).getId(), variables1);
        System.out.println("User Task1被完成了，此时流程已流转到User Task2");

        List<Task> list1 = taskService.createTaskQuery().taskAssignee("lili").list();
        Map<String, Object> variables2 = new HashMap<>();
        variables2.put("user4", "bobo");
        variables2.put("startTime", "2018-6-11T14:22:00"); // 设置定时边界任务的触发时间 注意：后面的时间必须是ISO 8601时间格式的字符串！！！
        taskService.complete(list1.get(0).getId(), variables2);

        List<Task> list2 = taskService.createTaskQuery().taskAssignee("bobo").list();
        if (list2 != null && list2.size() > 0) {
            for (Task task : list2) {
                System.out.println("任务ID：" + task.getId());
                System.out.println("任务的办理人：" + task.getAssignee());
                System.out.println("任务名称：" + task.getName());
                System.out.println("任务的创建时间：" + task.getCreateTime());
                System.out.println("流程实例ID：" + task.getProcessInstanceId());
                System.out.println("#######################################");
            }
        }
    }

}
